﻿// 7 公路村村通 (15分).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//几位数组都是从0开始的啊

#include <iostream>
using namespace std;

int main()
{
	int i, j, k, m, next, n, h, l, distance;
	int min;
	int total = 0;
	int flag = 1;
	//输入行列和道路数
	cin >> m >> n;
	//建立行列相等的二维数组
	int** a = new int* [m];

	for (i = 0; i < m; i++)
	{
		a[i] = new int[m];
	}
	//对角线无穷化
	for (i = 0; i < m; i++)
	{
		for (j = 0; j < m; j++)
		{
			a[i][j] = 999999;
		}//最开始每一个值默认距离为无穷，因为样例一开始给的矩阵是除对角线外都有值，忘记考虑不满矩阵的情况了
	}
	//输入每一条道路的距离
	for (i = 0; i < n; i++)
	{
		cin >> h;
		cin >> l;
		cin >> distance;
		a[h - 1][l - 1] = distance;
		a[l - 1][h - 1] = distance;


	}
	//新建一个记录数组visited
	int* visited = new int[m];
	for (i = 0; i < m; i++)
	{
		visited[i] = 0;//未访问是0
	}
	//开始遍历，以0点开始
	k = 0;
	visited[k] = 1;
	int start = 0;
	if (n < m - 1) { cout << "-1"; }
	else {
		while (1)
		{
			min = 999999;
			for (j = 0; j < m; j++)
			{
				if (a[k][j] < min && visited[j] == 0)
				{
					min = a[k][j];
					next = j;//记录最短值指向的点;
				}
			}

			start++;

			total = min + total;
			if (start < m - 1 && min == 999999)
			{
				flag = 0;
				break;
			}
			if (start == m - 1)
			{
				break;
			}
			visited[k] = 1;
			int normal = 1;

			k = next;


		}
		if (flag == 1) {

			cout << total;
		}
		else
		{
			cout << "-1";
		}
	}
}


